import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Select, Row, Radio, TimePicker, Modal } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import ProvincesCascader from '@/components/ProvincesCascader'
import UploadPic from '@/components/UploadPic'
import moment from 'moment'
import { getSupplierList, getTmpList, updateInfo, saveInfo, getCatList, getStoreInfo } from '@/services/supplier/store/baseInfo'
import RenderMap from '@/pages/platform/check/components/map'

const { Option } = Select

const { TextArea } = Input

const BaseInfo = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [provinceId, setProvinceId] = useState('') // 省
  const [cityId, setCityId] = useState('') // 市
  const [areaId, setAreaId] = useState('') // 区
  const [CatList, setCatList] = useState([])  // 行业分类
  const [businessList, setBusinessList] = useState([
    {
      id: '0',
      name: '百货'
    }
  ])  // 业务行业
  const [startTime, setStartTime] = useState('00:00:00')  // 开点时间
  const [endTime, setEndTime] = useState('23:59:59')  // 关店时间
  const [supplierLogo, setSupplierLogo] = useState('')
  const [showingImage, setShowingImage] = useState('')
  const [openLicense, setOpenLicense] = useState('')
  const [storeOriginal, setStoreOriginal] = useState('')
  const [supplierList, setSupplierList] = useState([])
  const [cooperateTypeList, setCooperateTypeList] = useState([
    {
      id: '1',
      name: '直营'
    },
    {
      id: '0',
      name: '加盟'
    },
    {
      id: '2',
      name: '未知'
    }
  ])  // 合作类型
  const [tmp, setTmp] = useState('请选择模板')
  const [template_id, setTemplate_id] = useState('')
  const [visible, setVisible] = useState(false)
  const [tmpList, setTmpList] = useState([])
  const [storeId, setStoreId] = useState(null)
  const [storeInfo, setStoreInfo] = useState({})
  const [lat, setLat] = useState(null)
  const [lon, setLon] = useState(null)

  useEffect(() => {
    init()
  }, [])
  const init = async () => {
    let id = props.location.query.id
    if (id) {
      setStoreId(id)
      await getStoreInfos(id)
    }
    await getSupplierLists()
    await getCatLists()
  }
  // 获取商铺信息
  const getStoreInfos = async id => {
    let params = {
      id
    }
    let res = await getStoreInfo(params)
    if (res.code === '0') {
      setStoreInfo(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)

    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return (
      <Col span={8}>
        <Form.Item label={`名称`}>
          {getFieldDecorator(`id`, {})
            (<Input />)}
        </Form.Item>
      </Col>
    )
  }
  // 按钮处理
  const handleBtn = type => {

  }
  // 选择省市区
  const selectAddress = (value, arr) => {
    setProvinceId(arr[0] ? arr[0].value : '')
    setCityId(arr[1] ? arr[1].value : '')
    setAreaId(arr[2] ? arr[2].value : arr[1].value)
  }
  // 选择营业时间
  const selectBusinessTime = (time, timeString, type) => {
    switch (type) {
      case 'start':
        setStartTime(timeString)
        break
      case 'end':
        setEndTime(timeString)
        break
    }
  }
  // 保存信息
  const submit = async () => {
    form.validateFields(async (err, values) => {
      console.log('Received values of form: ', values)
      let params = {
        ...values
      }
      if (!params.businessTime) params.businessTime = startTime + '-' + endTime
      params.provinceId = provinceId
      params.cityId = cityId
      params.areaId = areaId
      params.template_id = template_id
      params.lat = lat
      params.lon = lon
      params.isOpenOta = '0'
      params.isOpenCb = '1'
      params.loginType = '0'
      params.busStatus = '1'
      params.allBrowse = '0'
      params.deptId = '0'
      params.monBrowse = '0'
      params.payAlipay = '0'
      params.payWechat = '0'
      params.storeStatus = '1'
      params.storeSource = '1'

      if (storeId) params.id = storeId
      let res
      if (storeId) {
        res = await updateInfo(params)
      } else {
        res = await saveInfo(params)
      }
      if (res.code === '0') {
        alert(res.msg)
      } else {
        alert(res.msg)
      }
    })
  }
  // 获取商户列表
  const getSupplierLists = async () => {
    let res = await getSupplierList()
    if (res.code === '0') {
      setSupplierList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 打开模板弹出层
  const handleModal = async () => {
    if (!visible) await getTmpLists()
    setVisible(!visible)
  }
  // 选择模板
  const selectTmp = (e) => {
    let r = e.target.value
    setTmp(r.name)
    setTemplate_id(r.id)
    handleModal()
  }
  // 获取模板列表
  const getTmpLists = async () => {
    let res = await getTmpList()
    if (res.code === '0') {
      setTmpList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 获取行业分类列表
  const getCatLists = async () => {
    let params = {
      pageSize: 9999
    }
    let res = await getCatList(params)
    if (res.code === '0') {
      setCatList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 获取地图坐标
  const getLocation = (name, location) => {
    console.log(name, location)
    setLat(location.lat)
    setLon(location.lng)
    let obj = storeInfo
    obj.address = name
    setStoreInfo(obj)
  }

  return (
    <PageHeaderWrapper>
      {/* <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} /> */}
      <RenderButtom click={handleBtn} />
      <Row gutter={24}>
        <Col style={{width: '100%', height: '400px'}}>
          <RenderMap isNew={true} mapPosition={''} getLocation={getLocation}/>
        </Col>
        <Col span={12}>
          <Form.Item label="所属商户" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('supplierId', {
              initialValue: storeInfo.merchantsId
            })
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { supplierList && supplierList.map(r => <Option key={r.id} value={r.id}>{r.merchantName}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="门店名称" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('name', {
              initialValue: storeInfo.name
            })
              (<Input placeholder="请输入" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="合作类型" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('cooperateType', {
              initialValue: storeInfo.cooperateType
            })
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { cooperateTypeList && cooperateTypeList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <>
          { !storeId ?
          <Col span={12}>
            <Form.Item label="店铺模板" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('templateId', {})
                (<>
                  <Button type="primary" onClick={handleModal}>{tmp}</Button>
                  <Modal
                    title="店铺模板"
                    visible={visible}
                    onOk={handleModal}
                    onCancel={handleModal}
                  >
                    <Radio.Group onChange={selectTmp}>
                      {tmpList.map(r => <Radio key={r.id} value={r}>{r.name}</Radio>)}
                    </Radio.Group>
                  </Modal>
                </>)}
            </Form.Item>
          </Col>
          : ''}
        </>
        <Col span={12}>
          <Form.Item label="店铺位置" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('storeAddress', {
              initialValue: [storeInfo.provinceId, storeInfo.cityId, storeInfo.areaId],
            })
              (<ProvincesCascader onChange={selectAddress} />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="详细地址" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('address', {
              initialValue: storeInfo.address
            })
              (<Input placeholder="请输入" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="行业分类" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('parentCatId', {
              initialValue: storeInfo.parentCatId
            })
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { CatList && CatList.map(r => <Option key={r.id} value={r.id}>{r.catName}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="业务行业" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('industryId', {
              initialValue: storeInfo.industryId
            })
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { businessList && businessList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="联系电话" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('phone', {
              initialValue: storeInfo.phone
            })
              (<Input placeholder="请选择" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="联系人" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('contactPerson', {
              initialValue: storeInfo.contactPerson
            })
              (<Input placeholder="请选择" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="营业状态" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('busStatus', {
              initialValue: storeInfo.busStatus
            })
              (<Radio.Group>
                <Radio value={'0'}>营业中</Radio>
                <Radio value={'1'}>暂停营业</Radio>
              </Radio.Group>)}
          </Form.Item>
        </Col>
        {
          storeInfo.businessTime ?
          <Col span={12}>
            <Form.Item label="营业时间" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('businessTime', {
                initialValue: storeInfo.businessTime
              })
                (<>
                  <TimePicker format="HH:mm" onChange={(time, timeString) => selectBusinessTime(time, timeString, 'start')} defaultOpenValue={moment(storeInfo.businessTime.split('-')[0], 'HH:mm')} style={{width: '50%'}} />
                  <TimePicker format="HH:mm" onChange={(time, timeString) => selectBusinessTime(time, timeString, 'end')} defaultOpenValue={moment(storeInfo.businessTime.split('-')[1], 'HH:mm')} style={{width: '50%'}} />
                </>)}
            </Form.Item>
          </Col>
          : ''
        }
        <Col span={12}>
          <Form.Item label="商品管理密码" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('goodsPwd', {
              initialValue: storeInfo.goodsPwd
            })
              (<Input placeholder="请选择" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="营销管理密码" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('marketPwd', {
              initialValue: storeInfo.marketPwd
            })
              (<Input placeholder="请选择" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="退款密码" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('refundPwd', {
              initialValue: storeInfo.refundPwd
            })
              (<Input placeholder="请选择" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="排序" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('sort', {
              initialValue: storeInfo.sort
            })
              (<Input placeholder="请选择" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="是否默认" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('isDefault', {
              initialValue: storeInfo.isDefault
            })
              (<Radio.Group>
                <Radio value={'1'}>是</Radio>
                <Radio value={'0'}>否</Radio>
              </Radio.Group>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="是否上架" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('status', {
              initialValue: storeInfo.isDisplay
            })
              (<Radio.Group>
                <Radio value={'0'}>上架</Radio>
                <Radio value={'1'}>下架</Radio>
              </Radio.Group>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="是否推荐到首页" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('isIndexRecommend', {
              initialValue: storeInfo.isIndexRecommend
            })
              (<Radio.Group>
                <Radio value={'1'}>推荐</Radio>
                <Radio value={'0'}>不推荐</Radio>
              </Radio.Group>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="商户是否认证" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('isApproveStore', {
              initialValue: storeInfo.isApproveStore
            })
              (<Radio.Group>
                <Radio value={'1'}>认证</Radio>
                <Radio value={'0'}>未认证</Radio>
              </Radio.Group>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="门店LOGO" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('supplierLogo', {
              initialValue: storeInfo.supplierLogo
            })
              (<UploadPic
                maxLoad={1}
                imageUrl={storeInfo.supplierLogo}
                action="/Amaidan-Goods-Web/common/uploadImage"
              />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="上传营业执照" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('openLicense', {
              initialValue: storeInfo.openLicense
            })
              (<UploadPic
                maxLoad={1}
                imageUrl={storeInfo.openLicense}
                action="/Amaidan-Goods-Web/common/uploadImage"
              />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="门店实景" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('storeOriginal', {
              initialValue: storeInfo.openLicense
            })
              (<UploadPic
                maxLoad={5}
                imageUrl={storeInfo.openLicense}
                action="/Amaidan-Goods-Web/common/uploadImage"
              />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="推广封面" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('showingImage', {
              initialValue: storeInfo.showingImage
            })
              (<UploadPic
                maxLoad={1}
                imageUrl={storeInfo.showingImage}
                action="/Amaidan-Goods-Web/common/uploadImage"
              />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="门店简介" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('storeDesc', {
              initialValue: storeInfo.storeDesc
            })
              (<TextArea />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="门店公告" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('storeAffiche', {
              initialValue: storeInfo.storeAffiche
            })
              (<TextArea />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="分享描述" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('desc', {
              initialValue: storeInfo.desc
            })
              (<TextArea />)}
          </Form.Item>
        </Col>
      </Row>
      <Button type="primary" onClick={submit}>确认</Button>
   </PageHeaderWrapper>
  )
}

export default Form.create()(BaseInfo)
